package com.dk.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dk.pojo.PersonRole;
import com.dk.pojo.TPerson;
import com.dk.service.PersonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

public class LoginRealm extends AuthorizingRealm {
    @Reference
    private PersonService personService;
    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法");
        TPerson tPerson = (TPerson) SecurityUtils.getSubject().getPrincipal();
        //查询菜单权限
        List<String> perms = personService.selectPermsByUserId(tPerson.getPid());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perms);

        return info;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        TPerson tPerson = personService.selectByTperson(username);
        if (tPerson == null){
            return null;
        }

        return new SimpleAuthenticationInfo(tPerson,tPerson.getPwd(), ByteSource.Util.bytes(tPerson.getSalt()),tPerson.getPname());
    }

}
